package com.itheima.stock.service.impl;

import com.itheima.stock.common.enums.ResponseCode;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.CaptchaRespVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
//import jdk.internal.joptsimple.internal.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserServiceImpl
 * @Author Carithly
 * @Description UserService实现类
 * @Date 2022/10/13 10:09
 * @Version 1.0.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    //验证码长度
    private static final int CAPTCHA_LENGTH = 4;
    //验证码过期时间
    private static final int CAPTCHA_EXPIRE_TIME = 60;
    //redis存储验证码key前缀
    private static final String CAPTCHA_REDIS_PREFIX = "captcha:";
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户登录
     *
     * @param loginReqVo
     * @return
     */
    @Override
    public R<LoginRespVo> login(LoginReqVo loginReqVo) {
        //参数校验
        if (loginReqVo == null
                || Objects.isNull(loginReqVo.getUsername())
                || Objects.isNull(loginReqVo.getPassword())
                || Objects.isNull(loginReqVo.getCode())
                || Objects.isNull(loginReqVo.getRkey())
        ) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //从redis中获取验证码
        String captchaFromRedis;
        try {
            captchaFromRedis = stringRedisTemplate.opsForValue().get(loginReqVo.getRkey());
        } catch (Exception e) {
            log.error("从redis中{}获取验证码失败", loginReqVo.getRkey());
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //校验
        if (!Objects.equals(captchaFromRedis, loginReqVo.getCode())) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //清除redis中的验证码
        try {
            stringRedisTemplate.delete(loginReqVo.getRkey());
        } catch (Exception e) {
            log.error("清除验证码{}失败", loginReqVo.getRkey());
        }
        //核心业务
        SysUser userData = sysUserMapper.selectByUsername(loginReqVo.getUsername());
        if (Objects.isNull(userData)
                || Objects.isNull(loginReqVo.getPassword())
                || !passwordEncoder.matches(loginReqVo.getPassword(), userData.getPassword())) {
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        LoginRespVo loginRespVo = new LoginRespVo();
        //数据封装
        BeanUtils.copyProperties(userData, loginRespVo);
        return R.ok(loginRespVo);
    }

    /**
     * 验证码
     *
     * @return
     */
    @Override
    public R<CaptchaRespVo> generateCaptcha() {
        //参数校验

        //核心业务
        String captcha = RandomStringUtils.randomNumeric(CAPTCHA_LENGTH);
        Long id = idWorker.nextId();
        String redisKey = CAPTCHA_REDIS_PREFIX + id.toString();
        try {
            stringRedisTemplate.opsForValue().set(redisKey, captcha, CAPTCHA_EXPIRE_TIME, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("验证码生成失败。。。。");
        }
        //数据封装
        CaptchaRespVo captchaRespVo = CaptchaRespVo.builder().rkey(redisKey).code(captcha).build();
        return R.ok(captchaRespVo);
    }


}
